package cn.com.egova.web.action;

import cn.com.egova.domain.User;
import cn.com.egova.service.UserService;
import cn.com.egova.utils.FastJsonUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by yuanchao on 2020/5/24.
 */
public class UserAction extends ActionSupport implements ModelDriven<User> {
    private static final long serialVersionUID = 243895493565989l;
    private User user = new User();
    private UserService userService;

    public void setUser(User user) {
        this.user = user;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String register() {
        userService.register(user);
        return LOGIN;
    }

    @Override
    public User getModel() {
        return user;
    }

    public String checkCode() {
        User user = userService.checkCode(this.user.getUser_code());
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter writer = response.getWriter();
            if (user != null) {
                writer.print("no");
            } else {
                writer.print("yes");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return NONE;
    }

    public String login() {
        User existUser = userService.login(user);
        if (existUser == null) {
            return LOGIN;
        } else {
            ActionContext.getContext().getSession().put("existUser", existUser);
            return "loginOK";
        }
    }

    public String exit() {
        ActionContext.getContext().getSession().remove("existUser");
        return LOGIN;
    }


    public String findAll() {
        List<User> list = userService.findAll();
        String jsonString = FastJsonUtil.toJSONString(list);
        FastJsonUtil.writeJson(ServletActionContext.getResponse(), jsonString);
        return NONE;
    }

}
